#!/usr/bin/env python3
"""
最终修复脚本：安全地处理重复应用
"""

import os
import sys
import uuid
from datetime import datetime

# 确保使用正确的路径
api_dir = os.path.join(os.path.dirname(__file__), 'api')
sys.path.insert(0, api_dir)

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.models import Base, User, App, Memory, MemoryAccessLog

# 创建数据库连接
DATABASE_URL = "sqlite:///./openmemory.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

db = SessionLocal()

try:
    # 获取默认用户
    user = db.query(User).filter(User.user_id == "default_user").first()
    if not user:
        print("❌ 默认用户不存在，请先运行 simple_fix.py")
        sys.exit(1)
    
    print("🧪 检查当前应用状态...")
    
    # 显示所有应用
    all_apps = db.query(App).filter(App.owner_id == user.id).all()
    print(f"\n📊 当前共有 {len(all_apps)} 个应用:")
    for app in all_apps:
        memory_count = db.query(Memory).filter(Memory.app_id == app.id).count()
        print(f"   - '{app.name}' (ID: {app.id}, 记忆: {memory_count})")
    
    # 查找OpenMemory相关应用（不区分大小写）
    openmemory_apps = db.query(App).filter(
        App.owner_id == user.id,
        App.name.ilike("%openmemory%")
    ).order_by(App.created_at).all()
    
    print(f"\n🔍 找到 {len(openmemory_apps)} 个OpenMemory相关应用")
    
    if len(openmemory_apps) > 1:
        print("🛠️ 发现重复应用，开始修复...")
        
        # 保留第一个创建的应用
        keep_app = openmemory_apps[0]
        merge_apps = openmemory_apps[1:]
        
        print(f"📌 保留应用: '{keep_app.name}' (ID: {keep_app.id})")
        print(f"📤 合并应用: {[f'{app.name} ({app.id})' for app in merge_apps]}")
        
        total_memories_moved = 0
        total_logs_moved = 0
        
        for merge_app in merge_apps:
            # 合并记忆
            memories = db.query(Memory).filter(Memory.app_id == merge_app.id).all()
            for memory in memories:
                memory.app_id = keep_app.id
                total_memories_moved += 1
            
            # 合并访问日志
            logs = db.query(MemoryAccessLog).filter(MemoryAccessLog.app_id == merge_app.id).all()
            for log in logs:
                log.app_id = keep_app.id
                total_logs_moved += 1
            
            # 删除重复应用
            db.delete(merge_app)
            print(f"   ✅ 合并 {merge_app.name}: {len(memories)} 条记忆, {len(logs)} 条日志")
        
        # 标准化保留应用的名称
        keep_app.name = "OpenMemory"
        keep_app.updated_at = datetime.now()
        db.commit()
        
        print(f"\n🎉 修复完成！")
        print(f"   保留应用: '{keep_app.name}' ({keep_app.id})")
        print(f"   合并记忆: {total_memories_moved} 条")
        print(f"   合并日志: {total_logs_moved} 条")
        
    elif len(openmemory_apps) == 1:
        app = openmemory_apps[0]
        print(f"✅ 已有一个OpenMemory应用: '{app.name}' (ID: {app.id})")
        
        # 标准化名称
        if app.name != "OpenMemory":
            app.name = "OpenMemory"
            app.updated_at = datetime.now()
            db.commit()
            print("📝 标准化应用名称为 'OpenMemory'")
            
    else:
        print("ℹ️  没有找到OpenMemory应用，创建一个新的")
        
        app = App(
            id=uuid.uuid4(),
            name="OpenMemory",
            owner_id=user.id,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
        db.add(app)
        db.commit()
        print("✅ 创建OpenMemory应用")
    
    # 最终确认
    final_apps = db.query(App).filter(App.owner_id == user.id).all()
    final_openmemory = db.query(App).filter(
        App.owner_id == user.id,
        App.name == "OpenMemory"
    ).first()
    
    if final_openmemory:
        memory_count = db.query(Memory).filter(Memory.app_id == final_openmemory.id).count()
        print(f"\n📊 最终状态:")
        print(f"   总应用数: {len(final_apps)}")
        print(f"   OpenMemory应用: '{final_openmemory.name}' (ID: {final_openmemory.id})")
        print(f"   关联记忆数: {memory_count} 条")
    
    print("\n✅ 修复脚本执行完成！")
    print("\n📝 下一步操作:")
    print("   1. 重启你的n8n服务")
    print("   2. 在n8n中使用MCP配置: http://localhost:8000/mcp/OpenMemory/sse/default_user")
    print("   3. 所有记忆将统一关联到 'OpenMemory' 应用")
    
finally:
    db.close()